import React from 'react'
import "../../../common/common.css"
import PubSub from 'pubsub-js';
import ContextComponent from '../ContextComponent';

export default function Communication() {
    return (
        <div>
            Communication
            <button className='returnButton'><a href="/">点击返回主菜单</a></button>
            <div className="explain">
                <h1>组件通信方式总结</h1>
                <h2>方式：</h2>
                <h3> props:</h3>
                (1).children props
                (2).render props
                <h3>消息订阅-发布：</h3>
                pubs-sub、event等等
                <h3>集中式管理：</h3>
                redux、dva等等
                <h3>conText:</h3>
                生产者-消费者模式
                <h1>组件间的关系</h1>
                父子组件:props
                兄弟组件(非嵌套组件)：消息订阅-发布、集中式管理
                祖孙组件(跨级组件)：消息订阅-发布、集中式管理、conText(用的少)
            </div>
            <div className="divider">
                <h2>props</h2>
                <PropsComponent />
            </div>
            <div className='divider'>
                <h2>消息订阅发布</h2>
                <PubSubComponent />
                <Child />
            </div>
            <div className="divider">
                <h2>redux</h2>
                <p>
                    这里不做代码演示,document里面有专门对redux进行详细说明的文档。其他项目中有专门对redux使用的案例。
                    <a href="https://mp.weixin.qq.com/s?src=3&timestamp=1668334939&ver=1&signature=xP*ZZ4FJz0-Uxu7tQEuemE0kFhqxRSGgHJw*tyk0acWLjKnI7o0fCLDu-40POIKGsfhoNeq3ACNzyG3AGFRP1m0SMkfoAwuj1IHHJRMtcus4Y-8UqexjKdMklo4VzjwY9Fd*pqZSdFmoLfJBo4hlQ64OtACpLPHR4H7yb7dfL4k=">推荐阅读</a>
                </p>
            </div>
            <div className="divider">
                <h2>context</h2>
                <ContextComponent />
            </div>
        </div>
    )
}

function PropsComponent() {
    const [propsData, setPropsData] = React.useState("这是父组件通过props传给子组件的值")
    function changeProps() {
        setPropsData(propsData => "值改变啦！")
    }
    return (
        <div>
            <h1>propsComponent</h1>
            <Child propsData={propsData}/>
            <button onClick={changeProps}>改变props</button>
        </div>
    )
}

function PubSubComponent() {
    function trans() {
        PubSub.publish('updataState', "这是PubSubComponent组件传递的消息")
    }
    React.useEffect(() => {
        let timer = trans
        return () => {
            PubSub.unsubscribe(timer)
            console.log("取消订阅");
        }
    }, [])
    return (
        <div>
            <h1>PubSubComponent</h1>
            <button onClick={trans}>传递数据给订阅者</button>
        </div>
    )
}

function Child(props) {
    const [pubsubData, setPubsubData] = React.useState("这是子组件")
    const { propsData} = props
    PubSub.subscribe('updataState', (_, pubsubData) => {
        setPubsubData(pubsubData)
    })
    return (
        <div>
            <h1>Child</h1>
            <p>{propsData}</p>
            <p>{pubsubData}</p>
        </div>
    )
}
